<template>
  <el-drawer v-bind="$attrs" ref="drawerRef" size="40%">
    <template #header>
      <h3>{{ formMode == 'add' ? '新增' : '编辑' }}</h3>
    </template>
    <template #default>
      <view class="sv-add">
        <el-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-width="80px"
          label-position="left"
        >
          <el-form-item v-if="formMode !== 'add'" prop="avatar_file" label="头像">
            <uni-file-picker
              :image-styles="{
                width: 100,
                height: 100
              }"
              :auto-upload="false"
              v-model="formData.avatar_file"
              fileMediatype="image"
              mode="grid"
              limit="1"
              @select="selectFile"
              @success="uploadSuccess"
              @fail="uploadFail"
            />
          </el-form-item>
          <el-form-item prop="username" label="用户名" required>
            <el-input v-model="formData.username" />
          </el-form-item>
          <el-form-item prop="nickname" label="昵称" required>
            <el-input v-model="formData.nickname" />
          </el-form-item>
          <el-form-item v-if="formMode == 'add'" prop="password" label="密码" required>
            <el-input v-model="formData.password" type="password" show-password />
          </el-form-item>
          <el-form-item v-if="formMode !== 'add'" prop="gender" label="性别">
            <el-radio-group v-model="formData.gender">
              <el-radio :label="item.key" v-for="item in genderlist" :key="item.key">
                {{ item.value }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="mobile" label="手机号码">
            <el-input v-model="formData.mobile" />
          </el-form-item>
          <el-form-item prop="email" label="邮箱">
            <el-input v-model="formData.email" />
          </el-form-item>
          <el-form-item prop="role" label="角色" required>
            <el-checkbox-group v-model="formData.role">
              <el-checkbox v-for="item in roleList" :key="item" :label="item.role_id" :min="1" />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item v-if="formMode !== 'add'" prop="my_invite_code" label="邀请码">
            <el-input v-model="formData.my_invite_code" disabled />
          </el-form-item>
          <el-form-item prop="dcloud_appid" label="可用APP" required>
            <el-checkbox-group v-model="formData.dcloud_appid">
              <el-checkbox v-for="item in appList" :key="item" :label="item.appid" :min="1" />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item prop="status" label="状态">
            <el-select v-model="formData.status" placeholder="状态">
              <el-option
                v-for="item in statuslist"
                :key="item.value"
                :label="item.value"
                :value="item.key"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </view>
    </template>
    <template #footer>
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="confirm">确认</el-button>
    </template>
  </el-drawer>
</template>

<script setup>
import { ref, watchEffect } from 'vue'
import { useSvidStore } from '@/store/svid.js'
import { useSysStore } from '@/store/sys'
import { assignOverride, uploadFile } from '@/utils/util'
import { getDictById } from '@/utils/sys'

const props = defineProps({
  formInit: {
    type: Object,
    default: {}
  },
  formMode: {
    type: String,
    default: 'add'
  }
})

const emits = defineEmits(['submit'])

// 表单数据
const formData = ref({})
// 初始数据
const initData = {
  _id: '',
  avatar_file: {},
  username: '',
  nickname: '',
  password: '',
  gender: 0,
  mobile: '',
  email: '',
  role: [],
  my_invite_code: '',
  dcloud_appid: [],
  status: 0
}

watchEffect(() => {
  // 表单数据初始化-预更新
  if (props.formMode !== 'add') {
    delete initData.password
    initData._id = ''
  } else {
    // 新增账号，需要删掉_id字段，添加password字段
    delete initData._id
    initData.password = ''
  }
  formData.value = assignOverride({ ...initData }, props.formInit)
})

// 校验规则 - 同步svid严格校验
const rules = ref({
  username: [
    {
      required: true,
      message: '请输入用户名'
    },
    {
      min: 3,
      max: 32,
      message: '用户名长度在 3 到 32 个字符'
    },
    {
      validator: (rule, value, callback) => {
        if (/^1\d{10}$/.test(value) || /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/.test(value)) {
          callback('用户名不能是：手机号或邮箱')
        }
        if (/^\d+$/.test(value)) {
          callback('用户名不能为纯数字')
        }
        if (/[\u4E00-\u9FA5\uF900-\uFA2D]{1,}/.test(value)) {
          callback('用户名不能包含中文')
        }
        return true
      }
    }
  ],
  nickname: [
    {
      required: true,
      message: '请输入昵称'
    },
    {
      min: 3,
      max: 32,
      message: '昵称长度在 3 到 32 个字符'
    },
    {
      validator: (rule, value, callback) => {
        if (/^1\d{10}$/.test(value) || /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/.test(value)) {
          callback('用户名不能是：手机号或邮箱')
        }
        if (/^\d+$/.test(value)) {
          callback('用户名不能为纯数字')
        }
        return true
      }
    }
  ],
  password: [
    {
      required: true,
      message: '请输入密码'
    },
    {
      min: 8,
      max: 16,
      message: '密码长度在 8 到 16 个字符'
    },
    {
      validator: (rule, value, callback) => {
        if (
          !new RegExp(
            /^(?![0-9]+$)(?![a-zA-Z]+$)(?![~!@#$%^&*_\-+=`|\\(){}[\]:;"'<>,.?/]+$)[0-9a-zA-Z~!@#$%^&*_\-+=`|\\(){}[\]:;"'<>,.?/]{8,16}$/
          ).test(value)
        ) {
          callback('密码必须为字母、数字和特殊符号任意两种的组合，密码长度必须在8-16位之间')
        }
        return true
      }
    }
  ],
  dcloud_appid: [{ required: true, message: '请选择可用APP', trigger: 'blur' }],
  role: [{ required: true, message: '请选择角色', trigger: 'blur' }]
})

// 账号状态字典
const statuslist = getDictById('uni_id_users_status')
// 账号性别字典
const genderlist = getDictById('uni_id_users_gender')

const roleList = useSvidStore().getRoles()

const appList = useSysStore().getApps()

const drawerRef = ref() // 抽屉
const formRef = ref() // 表单

// 关闭抽屉
function cancel() {
  drawerRef.value.close()
}
// 确认提交表单
function confirm() {
  formRef.value.validate(async (valid, fields) => {
    if (valid) {
      // 手动上传图片
      if (props.formInit.avatar_file?.url !== formData.value.avatar_file?.url) {
        console.log('==== 图标修改了才上传，否则不上传 :')
        // 图标修改了才上传，否则不上传
        const upRes = await uploadFile(formData.value.avatar_file, 'avatarstorage')
        formData.value.avatar_file.url = upRes.fileID // 替换云存储中网络地址
      }
      console.log('==== formData.value :', formData.value)

      emits('submit', { data: formData.value, mode: props.formMode })
      drawerRef.value.close()
    } else {
      console.log('==== 校验失败 :', fields)
    }
  })
}

/**
 * 图片
 */
// 手动选择上传图片
function selectFile(e) {
  const { extname, name, url } = e.tempFiles[0]
  formData.value.avatar_file = { extname, url, name: `${Date.now()}-${name}` } // 确保name唯一性
  console.log('==== selectFile :', formData.value.avatar_file)
}

function uploadSuccess(e) {
  console.log('==== uploadSuccess :', e)
  const { extname, name, url } = e?.tempFiles[0]
  formData.value.avatar_file = { extname, name, url }
}

function uploadFail(e) {
  uni.showToast({
    title: '图片上传失败' + e,
    icon: 'none'
  })
}
</script>

<style lang="scss">
.sv-add {
  width: 100%;
  height: 100%;
}
</style>
